package com.bysc.userservice.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.RedisConstant;
import com.bysc.commonutils.utils.RandomUtil;
import com.bysc.userservice.service.MailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/emailservice/email")
@Api(tags = "发送邮箱验证码")
public class MailController {
    @Autowired
    private MailService mailService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/send/{email}")
    @ApiOperation(value = "发送邮箱验证码")
    public Results code(@PathVariable String email) {
        //先从缓存取验证码
        String code = (String) redisTemplate.opsForValue().get(RedisConstant.EMAIL + email);
        if (!StringUtils.isEmpty(code)) {//判断缓存是否有验证码
            return Results.ok();
        }
        //生成四位数验证码
        code = RandomUtil.getFourBitRandom();
        //构建信息
        String massage = "验证码为：" + code + "。您正在登录或注册智创云社官网会员，此验证码5分钟内有效，请勿外传！";
        try {
            //发送邮件
            mailService.sendMail(email, "智创云社--高校社团智能协同生态系统", massage);
        } catch (Exception e) {
            e.printStackTrace();
            return Results.error().message("发送邮箱验证码失败");
        }
        redisTemplate.opsForValue().set(RedisConstant.EMAIL + email, code, 5, TimeUnit.MINUTES);
        return Results.ok();
    }
}
